'''
Created on Nov 20, 2019
@author: Liang.Li
'''
from http import HTTPStatus
from library.db.query import Filter
from library.db import accessor
from library.web.ws.rs_usr import Resource, UserManagerResource
from library.mail.sender import SMTPSender
import sys
import platform

from email.mime.text import MIMEText
import smtplib


class CAEResource(Resource):
    __existed_alg = {
        't_user': ('auto_id', ('userId', 'email', None, None, None, None)),
        't_status': ('id', ('userId', 'email', 'moduleId', None, None, None)),
        't_learn_record': ('id', ('userId', 'email', 'module_id', 'route_id', None, None)),
        't_test_record': ('id', ('userId', 'email', 'module_id', 'route_id', 'isfinished', None)),
        't_test_answer_items': ('id', (None, None, None, 'record_id', None, 'stepName'))
    }

    @classmethod
    def __parse(cls, table, data, queryString):
        if table in cls.__existed_alg:
            pk, params = cls.__existed_alg[table]
            params = [queryString.get(k, None) or data.get(
                k, None) if k else None for k in params]
            params.insert(0, table)
            return (True, pk, tuple(params))
        return (False, None, None)

    @Resource.route('/cae/sync/{table}', ['GET', 'POST'], need_login=True)
    def sync_data(self, table, __request__):
        table = 't_%s' % table
        if __request__.method == 'GET':
            qs = {**{'page': '0', 'length': '10', 'db': None}, **
                  {x[0]: x[1] for x in __request__.query_string if len(x) == 2}}
            try:
                page = int(qs['page'])
                length = int(qs['length'])
            except:
                page = 0
                length = 10
            ok, data, total = accessor.select(
                table, page=page, length=length, dbname=qs['db'])
            return self.response(data=data, total=total) if ok else self.response(HTTPStatus.INTERNAL_SERVER_ERROR, data)
        else:
            qs = {**{'userId': None, 'email': None}, **
                  {x[0]: x[1] for x in __request__.query_string if len(x) == 2}}
            data = __request__.data
            if isinstance(data, dict):
                data.pop('isUpload', None)
                ID = data.pop('id', None)
                if table not in ('t_test_record', 't_test_answer_items'):
                    ID = None
                columns = []
                values = []
                for k, v in data.items():
                    columns.append(k)
                    values.append(v)
                columns = ','.join(columns)
                ok, pk, params = self.__parse(table, data, qs)
                if ok:
                    with accessor.Session() as session:
                        if not (isinstance(ID, int) and ID):
                            ok, d, _, _ = session.callproc(
                                'p_exists', *params, reading=True)
                            if ok and d[0]:
                                ID = d[0][0].get('id', None)
                        if ID:
                            session.update(table, columns, values,
                                           Filter(pk, Filter.OP.EQUAL, ID))
                            return self.response()
                        if table not in ('t_user', 't_test_answer_items'):
                            ok, d, _, _ = session.callproc(
                                'p_get_userid', *(qs['userId'], qs['email']), reading=True)
                            if ok and d[0]:
                                columns += ',user_id'
                                values.append(d[0][0].get('id', None))
                        ok, params = session.insert(
                            table, columns, [values], pk)
                        return self.response(params=params) if ok else self.response(HTTPStatus.INTERNAL_SERVER_ERROR, params)
            return self.response(HTTPStatus.BAD_REQUEST)


class CAEUserResource(UserManagerResource):
    __slots__ = ('__mgr',)

    def __init__(self, user_manager):
        super().__init__(user_manager)
        self.__mgr = user_manager
    # @Resource.route('/cae/user/password/change', ['POST'], need_login=True)
    # def change_password(self, __request__):
    # 	data = __request__.data
    # 	if isinstance(data, dict):
    # 		ok, error = self.__mgr.change_password(data.get('okta', ''), data.get('oldpassword', ''), data.get('newpassword', ''))
    # 		return self.response() if ok else self.response(HTTPStatus.INTERNAL_SERVER_ERROR, error)
    # 	return self.response(HTTPStatus.BAD_REQUEST)
    # @Resource.route('/cae/user/password/forgot', ['POST'])
    # def forgot_password(self, __request__):
    # 	data = __request__.data
    # 	if isinstance(data, dict) and 'username' in data:
    # 		relayState = 'https://cae-healthcare-caneast-appservice-dev-001.azurewebsites.net/question.html'
    # 		ok, error = self.__mgr.forgot_password(data['username'], relayState=relayState)
    # 		return self.response() if ok else self.response(HTTPStatus.INTERNAL_SERVER_ERROR, error)
    # 	return self.response(HTTPStatus.BAD_REQUEST)
    # @Resource.route('/cae/user/password/forgot/rec/token', ['POST'])
    # def forgot_password_recovery_token(self, __request__):
    # 	data = __request__.data
    # 	if isinstance(data, dict) and 'recoveryToken' in data:
    # 		ok, error = self.__mgr.forgot_password_recovery_token(token=data['recoveryToken'])
    # 		return self.response() if ok else self.response(HTTPStatus.INTERNAL_SERVER_ERROR, error)
    # 	return self.response(HTTPStatus.BAD_REQUEST)
    # @Resource.route('/cae/user/password/forgot/new/pwd', ['POST'])
    # def forgot_password_new_pwd(self, __request__):
    # 	data = __request__.data
    # 	if isinstance(data, dict) and 'stateToken' in data:
    # 		ok, error = self.__mgr.forgot_password_new_pwd(token=data['stateToken'], newPWD=data['newPassword'])
    # 		return self.response() if ok else self.response(HTTPStatus.INTERNAL_SERVER_ERROR, error)
    # 	return self.response(HTTPStatus.BAD_REQUEST)
    # @Resource.route('/cae/user/password/forgot/ques', ['POST'])
    # def forgot_password_ques(self, __request__):
    # 	data = __request__.data
    # 	if isinstance(data, dict) and 'stateToken' in data:
    # 		ok, error = self.__mgr.forgot_password_ques(token=data['stateToken'], answer=data['answer'])
    # 		return self.response() if ok else self.response(HTTPStatus.INTERNAL_SERVER_ERROR, error)
    # 	return self.response(HTTPStatus.BAD_REQUEST)
    # @Resource.route('/cae/user/reset/password', ['GET', 'POST'])
    # def reset_password(self, __request__):
    # 	return (True, 'reset pwd ok')
    # 	# data = __request__.data
    # 	# if isinstance(data, dict) and 'username' in data:
    # 	#     ok, error = self.__mgr.forgot_password(data['username'], relayState='')
    # 	#     return self.response() if ok else self.response(HTTPStatus.INTERNAL_SERVER_ERROR, error)
    # 	# return self.response(HTTPStatus.BAD_REQUEST)
    # @Resource.route('/cae/user/recovery/question', ['GET', 'POST'])
    # def recovery_question(self, __request__):
    # 	data = __request__.data
    # 	if isinstance(data, dict) and 'oktaId' in data:
    # 		ok, error = self.__mgr.recovery_question(data.get('oktaId'), data.get('question', ''), data.get('answer', ''))
    # 		return self.response(data=data) if ok else self.response(HTTPStatus.INTERNAL_SERVER_ERROR, error)
    # 	return self.response(HTTPStatus.BAD_REQUEST)
    @Resource.route('/cae/test', ['GET'])
    def index(self, __request__):
        html = '<h1>Hello World!!!<h1>'
        # with open ("./web/test.html", "r") as hostingstart_file:
        # 	html += hostingstart_file.read()
        return self.response(data=html)

    # @Resource.route('/cae/user/send/email', ['GET', 'POST'])
    # def send_email(self, __request__):
    # 	# data = __request__.data
    # 	# recoveryToken = data['recoveryToken']
    # 	account = 'JohnWilson9093@gmail.com'
    # 	sender = SMTPSender(
    # 	        account=account,
    # 	        password='jw123$%^',
    # 	        host='smtp.gmail.com', port='465', ssl=True
    # 	    )
    # 	# msg = MIMEText('''
    # 	#     <form name='form1' action='https://cardinalb2b.oktapreview.com/api/v1/authn/recovery/token' method='post' id="form1">
    # 	#         <input type='hidden' name='recoveryToken' value='%s'/>
    # 	#         <input type='submit' value='index'></input>
    # 	#     </form>
    # 	#     ''' % recoveryToken, 'html', 'utf-8')
    # 	msg = MIMEText('''
    # 	    Hello World!!!
    # 	    ''', 'html', 'utf-8')

    # 	sender.send(msg=msg, from_addr=account, to_addrs='JohnWilson9093@gmail.com')
